<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>PDF to Image Preview</title>
    <!-- 引入在线pdf.js和pdf.worker.js -->
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.min.js"></script>
    <script>
      pdfjsLib.GlobalWorkerOptions.workerSrc =
        "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.min.js";
    </script> -->
    <style>
      .img-box {
        width: 500px;
        height: 500px;
      }
      .img-box img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    </style>
  </head>

  <body>
    <div class="img-box">
      <img id="pdfImage" src="" alt="PDF Image" />
    </div>

    <!-- 引入本地的pdf.js和pdf.worker.js -->
    <script src="./js/pdf.min.js"></script>
    <script>
      pdfjsLib.GlobalWorkerOptions.workerSrc = "./js/pdf.worker.min.js";
      const imageElement = document.getElementById("pdfImage");

      // 替换为你的PDF文件路径
      const pdfUrl = "./pdf/cert.pdf";

      // 获取PDF文件的二进制数据
      fetch(pdfUrl)
        .then((response) => response.arrayBuffer())
        .then((arrayBuffer) => {
          // 使用PDF.js解析ArrayBuffer
          const pdf = pdfjsLib.getDocument({ data: arrayBuffer });
          return pdf.promise;
        })
        .then((pdf) => {
          // 获取第一页
          return pdf.getPage(1);
        })
        .then((page) => {
          const scale = 1.5;
          const viewport = page.getViewport({ scale });

          const canvas = document.createElement("canvas");
          const context = canvas.getContext("2d");
          canvas.height = viewport.height;
          canvas.width = viewport.width;

          const renderContext = {
            canvasContext: context,
            viewport: viewport,
          };

          // 将PDF页面绘制到canvas上
          return page.render(renderContext).promise.then(() => canvas);
        })
        .then((canvas) => {
          // 将canvas转换为图片并显示
          imageElement.src = canvas.toDataURL("image/png");
        })
        .catch((error) => console.error("Error:", error));
    </script>
  </body>
</html>
